/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mindbox.mueblesalpes.negocio.jms;

import com.mindbox.mueblesalpes.negocio.entity.Promocion2X1;
import com.mindbox.mueblesalpes.negocio.mercadeo.MercadeoServiceLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

/**
 * Message Driven Bean encargado de la recepción de mensajes para Mercadeo
 * @author Catalina
 */
@MessageDriven(mappedName = "jms/PromocionTopic", activationConfig =  {
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "Durable"),
        @ActivationConfigProperty(propertyName = "clientId", propertyValue = "MercadeoMessageBean"),
        @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = "MercadeoMessageBean")
    })
public class MercadeoMessageBean implements MessageListener {

    @Resource
    private MessageDrivenContext mdc;

    @EJB
    MercadeoServiceLocal mercadeoService;
    
    public MercadeoMessageBean() {
    }

    /**
     * Método encargado de la recepción de mensajes
     * @param message
     */
    public void onMessage(Message message) {
        ObjectMessage msg = null;
        try {
            if (message instanceof ObjectMessage) {
                msg = (ObjectMessage) message;

                if(msg.getObject() instanceof Promocion2X1){
                    Promocion2X1 promocion = (Promocion2X1) msg.getObject();
                    mercadeoService.escribirLog(promocion);
                }else{
                    Logger.getLogger(MercadeoMessageBean.class.getName()).log(Level.SEVERE,
                            "Promoción de tipo equivocado: " + message.getClass().getName());
                }                
            } else {
                Logger.getLogger(MercadeoMessageBean.class.getName()).log(Level.SEVERE,
                        "Mensaje de tipo equivocado: " + message.getClass().getName());
            }
        } catch (JMSException e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        } catch (Throwable te) {
            te.printStackTrace();
        }
    }
    
}
